package com.shujia.flink.core

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.configuration.Configuration
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.streaming.api.functions.sink.{RichSinkFunction, SinkFunction}
import org.apache.flink.streaming.api.scala._

import java.sql.{Connection, DriverManager, PreparedStatement}

object Demo4ClazzNum {
  def main(args: Array[String]): Unit = {
    //创建flink环境
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    /**
     * 1、读取数据
     */
    val source: KafkaSource[String] = KafkaSource
      .builder[String]
      .setBootstrapServers("master:9092,node1:9092,node2:9092") //指定kafka 节点列表
      .setTopics("student") //指定读取的topic
      .setGroupId("my-group") //指定消费者组
      .setStartingOffsets(OffsetsInitializer.earliest) //读取所有的数据
      //.setStartingOffsets(OffsetsInitializer.latest())//从最末尾位点开始消费
      .setValueOnlyDeserializer(new SimpleStringSchema()) //指定反序列化的类
      .build

    //使用kafka source
    val studentDS: DataStream[String] = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")

    /**
     * 2、统计班级的人数
     */
    val kvDS: DataStream[(String, Int)] = studentDS
      .map(stu => {
        val clazz: String = stu.split(",")(4)
        (clazz, 1)
      })

    val clazzNumDS: DataStream[(String, Int)] = kvDS
      .keyBy(_._1) //安装班级分组
      .sum(1) //计算人数

    /**
     * 3、将统计结果保存到MySQL中
     */
    clazzNumDS.addSink(new RichSinkFunction[(String, Int)] {

      var con: Connection = _
      var stat: PreparedStatement = _

      //创建数据库连接
      override def open(parameters: Configuration): Unit = {
        //1、加载驱动
        Class.forName("com.mysql.jdbc.Driver")
        //2、创建数据库连接
        con = DriverManager.getConnection("jdbc:mysql://master:3306/bigdata?useUnicode=true&characterEncoding=UTF-8", "root", "123456")
        //编写sql
        //replace into : 替换插入，如果存在就替换，如果不存在就插入，表需要有主键
        stat = con.prepareStatement("replace into clazz_num values(?,?)")
      }

      //关闭数据库连接
      override def close(): Unit = {
        con.close()
      }

      //一条一条插入数据
      override def invoke(value: (String, Int), context: SinkFunction.Context): Unit = {
        //赋值
        stat.setString(1,value._1)
        stat.setInt(2,value._2)
        //执行sql
        stat.execute()
      }
    })
    env.execute()

  }
}
